package chatbot;

import chatbot.base.*;
import java.util.SortedSet;
import java.util.Comparator;
import java.util.Iterator;
import java.util.concurrent.ConcurrentSkipListSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import org.xeustechnologies.jcl.*;
import org.xeustechnologies.jcl.proxy.*;

public class Main {
    static SortedSet<Plugin> plugins;
    static JclObjectFactory factory;
    static JarClassLoader jcl;
    private static final Comparator<Plugin> compare = new Comparator<Plugin>() {
        public int compare(Plugin i, Plugin j) {
            int result = i.getName().compareTo(j.getName());
            return result;
        }
    };

    public static void main(String[] args) {
        plugins = new ConcurrentSkipListSet<Plugin>(compare);
        loadPlugins();
        attachEvents();
        attachListeners();
        ChatBot c;
        c = new SimpleChatBot();
        c.start();
    }
    public static void loadPlugins() {
        jcl = new JarClassLoader();
        ProxyProviderFactory.setDefaultProxyProvider( new CglibProxyProvider() );
        factory = JclObjectFactory.getInstance(true);
        File f = new File("./plugins/");
        String[] files = f.list();
        if (files != null) {
            for(int i = 0; i < files.length; i++) {
                String file = files[i];
                if (file.endsWith(".cbp")) {
                    loadPlugin(file);
                }
            }
        }
    }

    public static void loadPlugin(String file) {
        try {
            BufferedReader r = new BufferedReader(new FileReader("./plugins/"+file));
            String line;
            while((line = r.readLine()) != null) {
                if (line.startsWith(":")) {
                    //load plugin
                    jcl.add("./plugins/"+line.substring(1));
                }
                if (line.startsWith(";")) {
                    Plugin temp = (Plugin)factory.create(jcl, line.substring(1));
                    plugins.add(temp);
                    temp.open();
                }
            }
        } catch (Exception e) {

        }
    }
    public static void attachEvents() {
        Iterator<Plugin> it = plugins.iterator();
        while(it.hasNext()) {
            it.next().createEvents();
        }
    }
    public static void attachListeners() {
        Iterator<Plugin> it = plugins.iterator();
        while(it.hasNext()) {
            it.next().createListeners();
        }
    }
}
